package com.gome.oa.ess;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URLDecoder;

import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.CloseableHttpResponse;

/**
 *
 * @author: tang li
 * @date: 2016年8月21日
 * @desc: 
 *
 */
public class ExportExcel {
	private String username;
	private String password;
	private String startDate;
	private String endDate;
	
	public void setUsername(String username) {
		this.username = username;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}

	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}

	public String export(int attemp) throws Exception {
		
		if(attemp >= 3) {
			throw new Exception("大于重试次数, 终止。");
		}
		
		String exportUrl = "http://ess.gome.inc/ehm/kqrecored_exportXls.action?kqStartDate=" + startDate + "&kqEndDate=" + endDate;
		CloseableHttpResponse exportRes = Http.get(exportUrl);
		//未登录，自动登录
		if(exportRes.getStatusLine().getStatusCode() == 302 || !exportRes.containsHeader("Content-disposition")) {
			EssLogin essLogin = new EssLogin();
			essLogin.setUsername(username);
			essLogin.setPassword(password);
			essLogin.login();
			return export(attemp++);
		}
		else {
			InputStream in = exportRes.getEntity().getContent();
			String attchmentName = URLDecoder.decode(exportRes.getFirstHeader("Content-disposition").getValue(), "utf8");
			attchmentName = attchmentName.substring(attchmentName.indexOf("filename=") + 9);
			String tmpDir = System.getProperty("java.io.tmpdir");
			if(tmpDir == null) {
				tmpDir = "c:/";
			}
			File savePath = new File(tmpDir, attchmentName);
			FileOutputStream output = new FileOutputStream(savePath);
			IOUtils.copy(in, output);
			output.close();
			return savePath.getAbsolutePath();
		}
	}
}
